<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ include file="/WEB-INF/jsp/component/common.jsp" %>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge" ></meta>
    <title>详细内容</title>
    <link rel="stylesheet" href="${frames}/css/lib/bootstrap.min.css" type="text/css" type="text/css">
    <link rel="stylesheet" href="${frames}/css/lib/bootstrap-datetimepicker.min.css" type="text/css">
    <link rel="stylesheet" href="${newframe}/css/base/base.css" type="text/css">
    <link rel="stylesheet" href="${newframe}/css/common.css" type="text/css">
    <link rel="stylesheet" href="${frames}/css/picker.css" type="text/css">
    <link rel="stylesheet" href="${newframe}/css/select2.min.css" type="text/css">
    <link rel="stylesheet" href="${newframe}/css/beautify-time.css" type="text/css">
    <!--[if IE 8]>
    <link rel="stylesheet" href="${newframe}/css/base/IE8.css" type="text/css"/>
    <![endif]-->
    <style>
        .select2-container {
            width: 100% !important;
        }
        .btn-myStyle{
            background-color: #2c3e50;
            color:#fff;
        }
        /*.btn-primary{*/
            /*background-color: #000 !important;*/
        /*}*/
    </style>
    <%@ include file="/WEB-INF/jsp/component/commonBottom.jsp" %>
    <script src="${frames}/laydate/laydate.dev.js"></script>
    <script src="${assets}/bootstrapValidator/js/bootstrapValidator.js"></script>
    <script src="${assets}/bootstrapValidator/js/language/zh_CN.js"></script>
    <script src="${newframe}/js/select2.full.zh.js"></script>
    <script>
        $(document).ready(function(){
            initHosp("hospId");
            initWHosp("hospitalCode");
            getConfig("userSource");

            //修改时显示医院
            <c:if test="${hospital!=null}">
            addDepartment(${hospital.id},'${hospital.hospName}');
            $("#select2-hospId-container").text('${hospital.hospName}');
            //初始化科室
            $("input[name='hospId_officeCode']").removeAttr("checked");
            <c:forEach items="${assos}" var="asso">
            $("input[name='hospId_officeCode'][value='${asso.hospId}_${asso.officeCode}']").prop('checked',true);
            </c:forEach>
            </c:if>

            //修改时显示检测医院
            <c:if test="${wHospital!=null}">
            $("#select2-hospitalCode-container").text('${wHospital.hospitalName}');
            </c:if>

            $('#hospId').on("select2:select", function (evt) {

                // debugger;
                //这里是选中触发的事件
                //evt.params.data 是选中项的信息
//                $('#department_div').html('');
                var repo = evt.params.data;
//                $("#instrumentId").val(repo.id);
//                if(!!repo.id){
//                    addDepartment(repo.id,repo.hospName);
//                }
                if(!!repo.id){
                    if (addDepartment(repo.id,repo.hospName)){
                    }else {
                        $("#myForm").data('bootstrapValidator').destroy();

                        $('#myForm').data('bootstrapValidator', null);
                        $('#department_div').html('');
                        $("#hospId").empty();
                        formValidator();
                    }
                }
            });
            formValidator();
        });

        function formValidator() {
            $('#myForm').bootstrapValidator({
                message: 'This value is not valid',
                feedbackIcons: {
                    valid: 'glyphicon glyphicon-ok',
                    invalid: 'glyphicon glyphicon-remove',
                    validating: 'glyphicon glyphicon-refresh'
                },
                fields: {
                    "user.username": {
                        validators: {
                            notEmpty: true,
//                            regexp : {
//                                regexp : /^[a-zA-Z][a-zA-Z0-9_]*$/,
//                                message: "输入格式错误，请以英文开头,并且只能含有英文、数字和下划线"
//                            },
                            remote: {
                                type: "post",
                                delay: 500,
                                url: '${URL_SYS_USER_LIST_VALIDATEUSERNAME}',
                                data: function (validator) {
                                    return {
                                        username: validator.getFieldElements('user.username').val(),
                                        exception: '${user.username}'
                                    };
                                },
                                message: '该帐号已存在'
                            }
                        }
                    },
                    "user.mobile": {
                        validators: {
                            notEmpty: true,
                            digits: true,
                            remote: {
                                type: "post",
                                delay: 500,
                                url: '${URL_SYS_USER_LIST_VALIDATEMOBILE}',
                                data: function (validator) {
                                    return {
                                        mobile: validator.getFieldElements('user.mobile').val(),
                                        exception: '${user.mobile}'
                                    };
                                },
                                message: '该手机号码已存在'
                            }
                        }
                    },
                    "user.email": {
                        validators: {
//                            notEmpty: true,
                            emailAddress: true,
                            remote: {
                                type: "post",
                                delay: 500,
                                url: '${URL_SYS_USER_LIST_VALIDATEEMAIL}',
                                data: function (validator) {
                                    return {
                                        email: validator.getFieldElements('user.email').val(),
                                        exception: '${user.email}'
                                    };
                                },
                                message: '该邮箱已存在'
                            }
                        }
                    },
                    "user.password": {
                        validators: {
                            notEmpty: true,
                            stringLength:{
                                max:20,
                                min:6
                            }
                        }
                    },
                    "user.realName": {
                        validators: {
                            notEmpty: true
                        }
                    },
                    "doctor.hospId": {
                        validators: {
                            notEmpty: true,
                        }
                    }
                }
            }).on('success.form.bv', function (e) {
                e.preventDefault();
                var _url="";
                if($("#id").val() == null || $("#id").val() == ''){
                    _url =  '${URL_HL_DOCTOR_SAVE}';
                }else{
                    _url =  '${URL_HL_DOCTOR_UPDATE}';
                }
                $.ajax({
                    url: _url,
                    type: 'post',
                    data: $('#myForm').serialize(),
                    async: false, //默认为true 异步
                    error: function () {
                        alert('error');
                    },
                    success: function (data) {
                        closeFrame();
                    }
                });
            });


        }

        //关闭并刷新
        function closeFrame() {
            window.parent.closeModal();
        }

        function formatRepo(repo) {
            if (repo.loading) return repo.text;
            var markup = "<div class='select2-result-repository clearfix'>" +
                "<div class='select2-result-repository__title'>" + repo.hospName + "</div></div>";
            return markup;
        }
        function formatRepoSelection(repo) {
            return repo.hospName;
        }

        function formatWRepo(repo) {
            if (repo.loading) return repo.text;
            var markup = "<div class='select2-result-repository clearfix'>" +
                "<div class='select2-result-repository__title'>" + repo.hospitalName + "</div></div>";
            return markup;
        }
        function formatWRepoSelection(repo) {
            return repo.hospitalName;
        }



        function initHosp(id){
            $("#"+id).select2({
                placeholder: '请选医院',
                ajax: {
                    url: '${URL_HL_HOSPITAL_SELECT}',
                    dataType: 'json',
                    type: "post",
                    delay: 250,
                    data: function (params) {
                        var data=new Object();
                        data["iDisplayLength"]=10;
                        if(params.page==undefined){
                            data["iDisplayStart"]=0;
                        }else {
                            data["iDisplayStart"]= (params.page-1)*10;
                        }
                        if(params.term!=undefined){
                            data["hospName"]= params.term;
                        }
                        return data;
                    },
                    processResults: function (data, params) {
                        params.page = params.page || 1;
                        return {
                            results: data.data,
                            pagination: {
                                more: (params.page * 10) < data.msg
                            }
                        };
                    },
                    cache: true
                },
                escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
                minimumInputLength: 0,
                templateResult: formatRepo, // omitted for brevity, see the source of this page
                templateSelection: formatRepoSelection // omitted for brevity, see the source of this page
            });
        }

        function initWHosp(id){
            $("#"+id).select2({
                placeholder: '请选医院',
                ajax: {
                    url: '${URL_W_HOSPITAL_SELECT}',
                    dataType: 'json',
                    type: "post",
                    delay: 250,
                    data: function (params) {
                        var data=new Object();
                        data["iDisplayLength"]=10;
                        if(params.page==undefined){
                            data["iDisplayStart"]=0;
                        }else {
                            data["iDisplayStart"]= (params.page-1)*10;
                        }
                        if(params.term!=undefined){
                            data["hospitalName"]= params.term;
                        }
                        return data;
                    },
                    processResults: function (data, params) {
                        params.page = params.page || 1;
                        return {
                            results: data.data,
                            pagination: {
                                more: (params.page * 10) < data.msg
                            }
                        };
                    },
                    cache: true
                },
                escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
                minimumInputLength: 0,
                templateResult: formatWRepo, // omitted for brevity, see the source of this page
                templateSelection: formatWRepoSelection // omitted for brevity, see the source of this page
            });
        }

        /**
         * 在当前页面添加医院信息
         * */
        function addDepartment(id,hospName){
            var departmentHtml = "";
            $.ajax({
                url:'${URL_HL_HOSPITAL_DEPARTMENT_GET}',
                type:'post',
                data:'id='+id,
                async : false, //默认为true 异步
                dataType : 'json',
                error:function(){
                    alert('error');
                },
                success:function(data){
                    for(var i=0;i<data.data.length;i++){
                        departmentHtml += ''
                            +'<label class="col-sm-3">'
                            +'<label class="checkbox-inline">'
                            +'<input type="checkbox" name="hospId_officeCode"';
                        //默认第一个科室为该医生所在医院的科室
                        if(i==0){
                            departmentHtml += ' checked="checked" ';
                        }
                        departmentHtml += ''
                            +' onchange="checkDepartment(this)"'
                            +' value="' + id+"_"+data.data[i].id + '"> ' + data.data[i].showName
                            +'</label>'
                            +'</label>'
                        ;
                    }
                    if(departmentHtml!=""){
                        departmentHtml = '<div class="form-group">'+departmentHtml+'</div>';
                    }
                }
            });
            if(departmentHtml==""){
                top.bootbox.dialog({
                    message: "由于 "+hospName+" 没有设置科室，系统自动取消与该医院的关联",
                    buttons: {
                        OK: {
                            label: "确定",
                            className: "btn-myStyle"
                        }
                    }
                })
                return false;
            }else{
                $("#department_div").empty();
                $("#department_div").append(departmentHtml);
                return true;
            }
        }

        /**
         * 判断医院下面的科室是否没有选中一个，若是，则提示必选，并阻止其取消选中
         * */
        function checkDepartment(department){
            var hospId_officeCode_Arr = department.value.split("_");
            var departmentListChecked = false;
            $("input[name='hospId_officeCode'][value^="+hospId_officeCode_Arr[0]+"_"+"]").each(function(){
                if(this.checked){
                    departmentListChecked = true;
                    return false;
                }
            });
            if(!departmentListChecked){
                department.checked = true;
                top.bootbox.dialog({
                    message: "在该医院下，必须选中至少一个科室",
                    buttons: {
                        OK: {
                            label: "确定",
                            className: "btn-myStyle",
                            callback: function () {

                            }
                        },
                    }
                });
            }
        }
        function getConfig(code){
            $.ajax({
                url:"${URL_SYS_CONFIG_LIST_GETCONFIG}",
                type:'post',
                data:'configName='+code,
                error:function(){
                    alert('error');
                },
                success:function(data){
                    var objs = document.getElementById(code);
                    objs.options.length = 1;
                    var area = JSON.parse(data).data;
                    for(var i=0;i<area.length;i++){
                        var childOption = document.createElement("option");
                        childOption.value = area[i].key;
                        childOption.innerHTML = area[i].value;
                        objs.appendChild(childOption);
                    }
                    $("#userSource option[value=${doctor.userSource}]").attr("selected", "selected");
                }
            });
        }

    </script>
</head>
<body style="width: 98%">
<form id="myForm" class="form-horizontal" method="post">
    <!-- 用户类型默认为医生 -->
    <input type="hidden" id="userKind" name="user.userKind" class="form-control" value="2">
    <input type="hidden"  name="user.id" value="${user.id}">
    <input type="hidden" id="id" name="doctor.id" value="${doctor.id}">
    <div class="clearfix">
        <div class="form-group col-sm-6">
            <label class="col-sm-4 control-label">登录帐号</label>
            <div class="col-sm-8">
                <input type="text" id="username" name="user.username" class="form-control" value="${user.username}">
            </div>
        </div>
        <div class="form-group col-sm-6">
            <label class="col-sm-4 control-label">手机号</label>
            <div class="col-sm-8">
                <input type="text" id="mobile" name="user.mobile" class="form-control" value="${user.mobile}">
            </div>
        </div>
        <div class="form-group col-sm-6">
            <label class="col-sm-4 control-label">邮箱地址</label>
            <div class="col-sm-8">
                <input type="text" id="email" name="user.email" class="form-control" value="${user.email}">
            </div>
        </div>
        <div class="form-group col-sm-6">
            <label class="col-sm-4 control-label">密码</label>
            <div class="col-sm-8">
                <input type="text" id="password" name="user.password" class="form-control" value="">
            </div>
        </div>
        <div class="form-group col-sm-6">
            <label class="col-sm-4 control-label">真实姓名</label>
            <div class="col-sm-8">
                <input type="text" id="realName" name="user.realName" class="form-control" value="${user.realName}">
            </div>
        </div>
        <div class="form-group col-sm-6">
            <label class="col-sm-4 control-label">医生从医编号</label>
            <div class="col-sm-8">
                <input type="text" id="drCode" name="doctor.drCode" class="form-control" value="${doctor.drCode}">
            </div>
        </div>
        <div class="form-group col-sm-6">
            <label class="col-sm-4 control-label">职务</label>
            <div class="col-sm-8">
                <input type="text" id="position" name="doctor.position" class="form-control" value="${doctor.position}">
            </div>
        </div>
        <div class="form-group col-sm-6">
            <label for="userSource" class="col-sm-4 control-label">来源</label>
            <div class="col-sm-8">
                <select id="userSource" name="doctor.userSource" class="form-control">
                </select>
            </div>
        </div>
        <div class="form-group col-sm-6">
            <label class="col-sm-4 control-label">医院</label>
            <div class="col-sm-8">
                <select id="hospId" name="hospId"  class="form-control">
                    <c:if test="${hospital!=null}"><option value="${hospital.id}">${hospital.hospName}</option></c:if>
                </select>
            </div>
        </div>
        <div class="form-group col-sm-6">
            <label class="col-sm-4 control-label">检测报告单医院</label>
            <div class="col-sm-8">
                <select id="hospitalCode" name="hospitalCode"  class="form-control">
                    <c:if test="${wHospital!=null}"><option value="${wHospital.hospitalCode}">${wHospital.hospitalName}</option></c:if>
                </select>
            </div>
        </div>
        <div class="form-group col-sm-12">
            <label class="col-sm-2 control-label">科室</label>
            <div class="col-sm-10" id="department_div">
            </div>
        </div>
    </div>
    <div class="modal-footer" style="text-align: center ">
        <button type="button" class="btn btn-default" data-dismiss="modal" id="closeModalButt" onclick="closeFrame()">
            关闭
        </button>
        <button type="submit" class="btn btn-primary">保存</button>
    </div>
</form>
</body>
</html>